<template>
  <div>
    <el-button @click="addTreeNode">添加</el-button>
    <el-button @click="saveTreeNode">保存</el-button>
    <el-table
        :data="tableDataResult"
        style="width: 100%;margin-bottom: 20px;"
        :summary-method="getSummaries"
        show-summary
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
          prop="date"
          label="日期"
          sortable
          width="180">
      </el-table-column>
      <el-table-column
          prop="id"
          label="id"
          sortable
          width="50">
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"length
          sortable
          width="180">
      </el-table-column>
      <el-table-column
          prop="amount"
          label="订单金额">
      </el-table-column>
      <el-table-column
          prop="estimate"
          label="预估金额">
        <template slot-scope="scope">
          <el-input v-model="scope.row.estimate" v-if="!scope.row.children || scope.row.children.length == 0" @blur="getNodeSum"></el-input>
          <span v-else>{{scope.row.estimate}}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="projectImageProgress"
          width="130"
          align="center"
          label="工程形象进度(%)">
        <template slot-scope="scope">
          <!--                      <span :class="{'txt-h':isEdit}">{{calProjectImageProgress(scope.row)}}</span>-->
          <!--                      v-if="isEdit && (!scope.row.children || scope.row.children.length == 0)"-->
          <el-input
              class="number"
              v-if="isEdit && scope.row.parentId != 0"
              oninput=" value = value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"
              v-model.trim="scope.row.projectImageProgress" placeholder="请输入" ></el-input>
          <span v-else-if="isEdit && scope.row.parentId == 0">{{calProjectImageProgress(scope.row)}}</span>
          <span  v-else class="txt-h">{{scope.row.projectImageProgress}}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作">
        <template slot-scope="scope">
          <el-button @click="deleteNodeAndChildren(tableDataResult,scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <treeDetail v-if="treeDetailVisible" ref="treeDetailRef" @sendSelectRow="getSelectRow" @close="close"></treeDetail>
  </div>
</template>

<script >
import treeDetail from "./treeDetailCopy.vue";
import {validatenull} from "@/utils/validate"
export default {
  components: {
    treeDetail
  },
  computed:{
    calProjectImageProgress(){
      return (row)=>{
        let value = ''
        if (!validatenull(row['estimate']) &&  !validatenull(row['amount']) && row["amount"]!=0){
          value =Math.round((row['estimate'] /row['amount'])  * 10000 )  / 100
          if (row.parentId == 0){
            this.$set(row,'projectImageProgress',value)
          }
          return value
        }else{
          this.$set(row,'projectImageProgress','')
          return ''
        }
      }
    }
  },
  data(){
    return{
      isEdit:true,
      treeDetailVisible:false,
      tableData: [{
        id: 3,
        date: '2016-05-01',
        parentId:0,
        name: '王小虎3',
        address: '上海市普陀区金沙江路 1519 弄',
        amount:1000,
        children: [{
          id: 31,
          parentId:3,
          date: '2016-05-01',
          name: '王小虎31',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:''
        }, {
          id: 32,
          parentId:3,
          date: '2016-05-01',
          name: '王小虎32',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:''
        }, {
          id: 33,
          parentId:3,
          date: '2016-05-01',
          name: '王小虎33',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:'',
          children: [{
            id: 331,
            parentId:33,
            date: '2016-05-01',
            name: '王小虎331',
            address: '上海市普陀区金沙江路 1519 弄',
            children: [{
              id: 3311,
              parentId: 331,
              date: '2016-05-01',
              name: '3311',
              address: '上海市普陀区金沙江路 1519 弄',
              estimate:'',
            },{
              id: 3312,
              parentId: 331,
              date: '2016-05-01',
              name: '3312',
              address: '上海市普陀区金沙江路 1519 弄',
              estimate:'',
            }]
          }, {
            id: 332,
            parentId:33,
            date: '2016-05-01',
            name: '王小虎332',
            address: '上海市普陀区金沙江路 1519 弄',
            estimate:'',
          }, {
            id: 333,
            parentId:33,
            date: '2016-05-01',
            name: '王小虎333',
            address: '上海市普陀区金沙江路 1519 弄',
            estimate:'',
          }]
        }, {
          id: 44,
          parentId:3,
          date: '2016-05-01',
          name: '王小虎44',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:'',
          children: [{
            id: 441,
            parentId:44,
            date: '2016-05-01',
            name: '王小虎441',
            address: '上海市普陀区金沙江路 1519 弄',
            estimate:'',
          }, {
            id: 442,
            parentId:44,
            date: '2016-05-01',
            name: '王小虎442',
            address: '上海市普陀区金沙江路 1519 弄',
            estimate:'',
          }, {
            id: 443,
            parentId:44,
            date: '2016-05-01',
            name: '王小虎443',
            address: '上海市普陀区金沙江路 1519 弄',
            estimate:'',
          }]
        }]
      },{
        id: 100,
        date: '2016-05-01',
        name: '王小虎100',
        parentId:0,
        amount:500,
        address: '上海市普陀区金沙江路 1519 弄',
        children: [{
          id: 101,
          parentId:100,
          date: '2016-05-01',
          name: '王小虎101',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:''
        }, {
          id: 102,
          parentId:100,
          date: '2016-05-01',
          name: '王小虎102',
          address: '上海市普陀区金沙江路 1519 弄',
          estimate:''
        }]}
      ],
      tableDataOrigin:[],
      tableDataResult:[],
      tableDataArray:[]
    }
  },
  created() {
    this.tableDataOrigin = JSON.parse(JSON.stringify(this.tableData)) ;

    this.tableDataResult = this.tableData

  },
  methods:{
    addTreeNode(){
      this.treeDetailVisible = true ;
      // this.markTreeAWithB(this.tableDataOrigin,this.treeToArray(this.tableData)) ;
      this.$nextTick(()=>{
        this.$refs.treeDetailRef.init(this.tableDataResult) ;
      })
    },
    //// 示例：删除ID为2的节点及其所有子节点
    // deleteNodeAndChildren(treeData, 2);
    deleteNodeAndChildren(tableDataResult, nodeId) {
      function deleteNode(nodes) {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === nodeId) {
            nodes.splice(i, 1);
            return true;
          }
          if (nodes[i].children && deleteNode(nodes[i].children)) {
            return true;
          }
        }
        return false;
      }
      return deleteNode(tableDataResult);
    },
    calculateTotalEmployees(node) {
      let total = Number(node.estimate) || 0;
      if (node.children) {
        node.children.forEach(child => {
          total += this.calculateTotalEmployees(child); // 使用组件的实例方法递归计算
        });
      }
      return total;
    },
    // getNodeSum(tableData){
    //   tableData.map(node => {
    //     node.estimate = this.calculateTotalEmployees(node); // 添加到每个节点中
    //     if (node.children){
    //       this.getNodeSum(node.children);
    //     }
    //   });
    // },
    getSelectRow(data){
      this.tableDataArray = []
      //平铺tableDataResult
      this.tableDataArray = this.getTableDataArray(this.tableDataResult,this.tableDataArray)
      //合并比较数据
      this.tableDataArray = this.duiBiShuJu(this.tableDataArray,data)
      this.$nextTick(()=>{
        //转成树形
        this.tableDataResult = this.buildTree(this.tableDataArray)
        //刷新合计
        this.getNodeSum()
      })
      // this.tableDataResult = data
    },

    getTableDataArray(dataResult,dataArray){
      dataResult.forEach(item=>{
        if(item.children){
          this.getTableDataArray(item.children,dataArray)
          Vue.delete(item,'children')
          dataArray.push(item)
        }else{
          dataArray.push(item)
        }
      })
      return dataArray
    },

    duiBiShuJu(dataArray,data){
      const arr = []
      for (let i = 0; i < dataArray.length; i++) {
        const r = data.filter(d => d.id == dataArray[i].id)
        if(r.length==1){
          arr.push(dataArray[i]);
        }
      }

      data.forEach(item=>{
        const r = dataArray.filter(d => d.id == item.id)
        if(r.length==0){
          arr.push(item);
        }
      })

      return arr
    },

    buildTree222(items, parentId = 0) {
      return items
          .filter(item => item.parentId === parentId) // 过滤出当前父节点的子节点
          .map(item => ({
            ...item,
            children: this.buildTree(items, item.id) // 递归调用以构建子节点
          }));
    },


    buildTree(items, parentId = 0) {
      return items
          .filter(item => item.parentId === parentId) // 过滤出当前父节点的子节点
          .map(item => {
            let children = this.buildTree(items, item.id)
            if(children && children.length > 0){
              return ({...item, children: children })// 递归调用以构建子节点
            }else{
              return item
            }
          });
    },

    close(){
      this.treeDetailVisible = false ;
    },
    markTreeAWithB(treeA, treeB) {
      // 辅助函数，用于查找id是否存在于B中
      function findInTreeB(id) {
        for (const item of treeB) {
          if (item.id == id) {
            return true;
          }
        }
        return false;
      }

      // 辅助函数，用于递归遍历和标记树A
      function traverseAndMark(node) {
        if (findInTreeB(node.id)) {
          node.disabled = true; // 如果在B中找到，标记为true
        } else {
          node.disabled = false; // 如果不在B中，标记为false，虽然这在某些情况下可能是多余的，取决于你的具体需求
        }
        if (node.children) {
          node.children.forEach(child => traverseAndMark(child)); // 递归处理子节点
        }
      }

      // 对树A进行遍历和标记
      treeA.forEach(node => traverseAndMark(node));

      console.log("treeA:",treeA)
    },
    /**
     * 数据扁平化
     * @param tree
     * @returns
     */
    treeToArray(tree) {
      let res = []
      for (const item of tree) {
        const { children, ...i } = item
        if (children && children.length) {
          res = res.concat(this.treeToArray(children))
        }
        res.push(i)
      }
      return res
    },
    addToTree(data,willInsertData) {
      data.map(item=>{
        item.estimate = this.getSum(item.children) ;
        if (item.id == willInsertData.parentId){
          if (item.children){
            item.children.push(willInsertData);
          }else{
            item.children = [] ;
            item.children.push(willInsertData);
          }
        }
        if (item.children){
          this.addToTree(item.children,willInsertData);
        }
      })
    },
    getNodeSum(){
      this.getNodeSum2(this.tableDataResult,0)
    },
    getNodeSum2(tableData,sum) {
      tableData.map(item=>{
        if (item.children){
          const sumC = this.getNodeSum2(item.children,0)
          this.$set(item,"estimate",sumC)
          sum += sumC
        }else{
          sum +=  !item.estimate ? 0 : Number(item.estimate)
        }
      })
      return sum;
    },


    getSum(data){
      if (!data) return ;
      let sum = 0 ;
      data.map(item=>{
        sum += !item.estimate ? 0 : Number(item.estimate);
      })
      return sum ;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    saveTreeNode(){
      console.log("-----:",this.tableDataResult)
    }
  }
}
</script>

<style scoped>

</style>
